<template>
	<view class="center-box">
		<view class="mr30 flex align-center">
			<u-navbar back-icon-name="arrow-left" :title-bold="true" title-size="36" :border-bottom="false" back-icon-color="#333333" :title="title">
				<view class="navbar-right" slot="right" @click="l.to('/pages/home/gropInfo')">
					<image src="../../static/icon.png" class="w30 h30" mode=""></image>
				</view>
			</u-navbar>
		</view>
		<view class="center-list">
			
			<view class="private-center" v-for="(item, index) in 1" :key="index">
				<view class="flex" >
					<image src="../../app.png" class="w90 h90 r45" mode="" ></image>
					<view class="left-box ml30">123</view>
				</view>

				<view class="flex justify-between" v-for="(item, index) in 1" :key="index">
					<view class="w1"></view>
					<view class="flex">
						<view class="right-box mr30">321</view>
						<image src="../../app.png" class="w90 h90 r45" mode=""></image>
					</view>
				</view>
			</view>

			<view class="fiex-btn">
				<view class="">
					<view class="flex align-center justify-between">
						<i class="cuIcon-emojifill f60 mr24" style="color: #B3B3B3;"></i>
						<u-input :custom-style="bgColor" v-model="msg" :height="70" :maxlength="-1" uto-height="true" :clearable="false" type="textarea" :border="false" />
						<view class="ml24 w80 h70 lh70 text-center r35 f20" style="background-color: #FAFAFA;" @click="setMsg">发送</view>
					</view>
					<view class="flex pt25 h110">
						<image src="../../static/img/voice.png" class="w44 h44 mr95" mode=""></image>
						<image src="../../static/img/liwu.png" class="w44 h44 mr95" mode=""></image>
						<image src="../../static/img/album.png" class="w44 h44 mr95" mode=""></image>
						<image src="../../static/img/map.png" class="w44 h44 mr95" mode=""></image>
						<image src="../../static/img/phone1.png" class="w44 h44 mr95" mode=""></image>
						<image src="../../static/img/vide.png" class="w44 h44" mode=""></image>
					</view>
				</view>
			</view>
		</view>

		<view class="foot_box"></view>
		<!-- 加载提示 -->
		<yy-loading text="加载中.." mask="true" click="true" ref="loading"></yy-loading>
		<!-- 信息提示-->
		<u-toast ref="uToast" />
	</view>
</template>

<script>
import TIM from 'tim-js-sdk';

export default {
	data() {
		return {
			bgColor: {
				backgroundColor: '#FAFAFA',
				paddingLeft: '20rpx'
			},
			background: {
				backgroundColor: 'transparent',
				fontFamily: 'PingFang SC',
				fontWeight: 600
				// font-weight: ;
				// 导航栏背景图
				// background: 'url(https://cdn.uviewui.com/uview/swiper/1.jpg) no-repeat',
				// 还可以设置背景图size属性
				// backgroundSize: 'cover',
			},
			title: '酱酱',
			msg: '',
			type: 'password',
			height: 70,
			userUnfo: {},
			userList: [],
			// msgList: {},
			userMsgId: {},
			msgList: [],
		};
	},
	onShow() {
	},
	onLoad(e) {
		this.title = e.gropName
		
		// let onSdkNotReady = function(event) {
		// 	// 如果想使用发送消息等功能，接入侧需驱动 SDK 进入 ready 状态，重新调用 login 接口即可，如下所示：
		// 	tim.login({ userID: uni.getStorageSync('userInfo').id, userSig: 'your userSig' });
		// };
		// 打开某个会话时，第一次拉取消息列表

		// this.listFrom();
		// this.login();
		// this.message();
		// this.getMsgList()
		
	},
	methods: {
		async listFrom() {
			const res = await this.$u.get('/api/user/group/list');
			console.log('res==>', res);
		},
		getMsgList() {
			var that = this
			var usrId = this.userMsgId.followUid + ''
			// let promiseList = this.tim.getConversationProfile(`C2C${usrId}`);
			// promiseList.then(function(imResponse) {
			//   // 获取成功
			//   that.msgList = imResponse.data.conversation.lastMessage.payload.text
			//   console.log('// 会话资料', imResponse.data.conversation); // 会话资料
			// }).catch(function(imError) {
			//   console.warn('getConversationProfile error:', imError); // 获取会话资料失败的相关信息
			// });
			
			let promise = this.tim.getMessageList({ conversationID: `C2C${usrId}`, count: 15 });
			promise.then(function(imResponse) {
				const messageList = imResponse.data.messageList; // 消息列表。
				const nextReqMessageID = imResponse.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
				const isCompleted = imResponse.data.isCompleted; // 表示是否已经拉完所有消息。
			});
			
		},
		
		async login() {
			var that = this;
			const res = await this.$u.get('api/user/sig', {
				identifier: uni.getStorageSync('userInfo').id
			});
			let promise = this.tim.login({
				userID: uni.getStorageSync('userInfo').id + '',
				userSig: res.data
			});
			promise
				.then(function(imResponse) {
					console.log('登录成功', imResponse.data); // 登录成功
					if (imResponse.data.actionStatus == 'OK') {
						that.message();
					}
					if (imResponse.data.repeatLogin === true) {
						// 标识账号已登录，本次登录操作为重复登录。v2.5.1 起支持
						console.log(imResponse.data.errorInfo);
					}
				})
				.catch(function(imError) {
					console.warn('login error:', imError); // 登录失败的相关信息
				});
		},
		message() {
			var that = this
			const meId = uni.getStorageSync('userInfo').id 
			var headImg = uni.getStorageSync('userInfo').headImg 
			// const messageList = []
			var usrId = this.userMsgId.followUid + ''
			let promise = this.tim.getMessageList({ conversationID: `C2C${usrId}`, count: 15 });
			promise.then(function(imResponse) {
				const messageList = imResponse.data.messageList; // 消息列表。
				const nextReqMessageID = imResponse.data.nextReqMessageID; // 用于续拉，分页续拉时需传入该字段。
				const isCompleted = imResponse.data.isCompleted; // 表示是否已经拉完所有消息。
				
				console.log('消息列表==>', messageList);
				that.msgList = messageList
				that.msgList.forEach( ( i => {
					
					if (i.from == meId) {
						i.avatar = headImg
					} else {
						i.avatar = that.userMsgId.headImg
					}
				}))
					console.log('i*************==>', that.msgList);
				
			});
			let userInfo = this.tim.getUserProfile({
			  userIDList: [`${usrId}`] // 请注意：即使只拉取一个用户的资料，也需要用数组类型，例如：userIDList: ['user1']
			});
			
			userInfo.then(function(imResponse) {
			  console.log('存储用户资料的数组',imResponse.data); // 存储用户资料的数组 - [Profile]
			}).catch(function(imError) {
			  console.warn('getUserProfile error:', imError); // 获取其他用户资料失败的相关信息
			});
		},

		onSdkReady() {
			let p = this.tim.createGroup({
				type: '11',
				name: ''
			});
		},

		back() {
			uni.navigateBack({
				delta: 1
			});
		},

		bindTextAreaBlur: function(e) {
			console.log(e.detail.value);
		},
		setMsg() {
			var that = this
			// 1. 创建消息实例，接口返回的实例可以上屏 this.userMsgId
			let message = that.tim.createTextMessage({
				to: that.userMsgId.followUid + '',
				conversationType: TIM.TYPES.CONV_C2C,
				// 消息优先级，用于群聊（v2.4.2起支持）。如果某个群的消息超过了频率限制，后台会优先下发高优先级的消息，详细请参考：https://cloud.tencent.com/document/product/269/3663#.E6.B6.88.E6.81.AF.E4.BC.98.E5.85.88.E7.BA.A7.E4.B8.8E.E9.A2.91.E7.8E.87.E6.8E.A7.E5.88.B6)
				// 支持的枚举值：TIM.TYPES.MSG_PRIORITY_HIGH, TIM.TYPES.MSG_PRIORITY_NORMAL（默认）, TIM.TYPES.MSG_PRIORITY_LOW, TIM.TYPES.MSG_PRIORITY_LOWEST
				// priority: TIM.TYPES.MSG_PRIORITY_NORMAL,
				payload: {
					text:  that.msg
				}
			});
			// 2. 发送消息
			let promise = that.tim.sendMessage(message);
			promise
				.then(function(imResponse) {
					// 发送成功
					console.log(imResponse);
					if (imResponse.code == 0) {
						that.msg = ''
						that.message()
						that.initListener()
					}
				})
				.catch(function(imError) {
					// 发送失败
					console.warn('sendMessage error:', imError);
				});
				that.tim.sendMessage(message);
		},
		initListener() {
			// 收到新消息
			let onMessageReceived = function(event) {
			  // event.data - 存储 Message 对象的数组 - [Message]
			  console.log(' event.data - 存储 Message ==>', event);
			};
			this.tim.on(TIM.EVENT.MESSAGE_RECEIVED, onMessageReceived);
			 console.log('收到新消息event==>', event);
			 console.log('this.tim.on(TIM.EVENT.MESSAGE_RECEIVED, onMessageReceived)==>', this.tim.on(TIM.EVENT.MESSAGE_RECEIVED, onMessageReceived));
		},
	}
};
</script>

<style lang="scss" scoped>
	page {
		width: 100%;
		height: 100%;
		background-color: #f7f5f7;
	}
.center-box {
	height: 100%;
	background-color: #f7f5f7;
	
	/deep/.u-input__textarea[data-v-904f09a4] {
		padding: 15rpx 0 !important;
		padding-left: 10rpx !important;
		border-radius: 10rpx !important;
	}
	
	.navbar-right {
		margin-right: 30rpx;
	}

	.center-list {
		width: 100%;
		height: 100%;
		padding-bottom: 200rpx;
		background-color: #f7f5f7;

		.private-center {
			width: 100%;
			height: 100%;
			padding: 37rpx 30rpx;
			
			background-color: #f7f5f7;

			.left-box {
				max-width: 400rpx;
				word-wrap: break-word;
				word-break: normal;
				padding: 27rpx 25rpx;
				background: #ffffff;
				margin-bottom: 50rpx;
				border-radius: 0px 20rpx 20rpx 20rpx;
			}

			.right-box {
				max-width: 400rpx;
				word-wrap: break-word;
				word-break: normal;
				padding: 27rpx 25rpx;
				background: #ffffff;
				margin-bottom: 50rpx;
				border-radius: 20rpx 0px 20rpx 20rpx;
			}
		}

		.fiex-btn {
			position: fixed;
			bottom: 0;
			width: 100%;
			padding: 20rpx 30rpx;
			background-color: #ffffff;
		}

		.fiex-btn1 {
			position: fixed;
			bottom: 220rpx;
			width: 100%;
			height: 200rpx;
			padding: 20rpx 30rpx;
			background-color: #ffffff;
		}
	}
}
</style>
